package com.example.InterFace2;

import org.json.JSONArray;
import org.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

@WebServlet(name = "ServletInTerFace2", value = "/ServletInTerFace2")
public class ServletGiveBikeMessage extends HttpServlet {

    private static final String DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
    //数据库连接地址
    private static final String URL = "jdbc:mysql://042.192.208.23/bike?characterEncoding=utf8&useSSL=true";
    private static final String USER_NAME="bike" ; //用户名
    private static final String PASSWORD="bike123456" ; //密码

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/json; charset=utf-8");
        String bikeName = request.getParameter("bike_name");
        PrintWriter out = response.getWriter();
        ConnectMysql connectMysql = new ConnectMysql();
        ResultSet rs = connectMysql.selectBike(bikeName);
        JSONArray jsonarray = new JSONArray();
        int count=0;
        try {
            while (rs.next()){

                count++;
                JSONObject jsonobj = new JSONObject();
//                String n = ;
//                System.out.println(n);product_kokua
                String bikeID = rs.getString("p_num");
                String bikeBrand=rs.getString("brand");
                connectMysql.addHot(bikeBrand);
                jsonobj.put("id",bikeID);
                jsonobj.put("brand",bikeBrand);
                jsonobj.put("bike_name",rs.getString("p_name"));
                jsonobj.put("bike_model",rs.getString("p_modle"));
                jsonobj.put("price_range",rs.getString("price_range"));
                jsonobj.put("pic_adr",connectMysql.giveImageAdr(bikeID));
                jsonarray.put(jsonobj);
            }

//            JSONObject js = new JSONObject();
//            List<String> list = connectMysql.giveHot();
//            js.put("HOT1", list.get(0));
//            js.put("HOT2",list.get(1));
//            js.put("HOT3",list.get(2));
//            js.put("HOT4",list.get(3));
//            jsonarray.put(js);
            if(count>0)out.println(jsonarray);
            else out.println("无结果");
            rs.close();
            connectMysql.close();
        }catch (Exception e){
            e.printStackTrace();
            out.println("系统内部错误");
            connectMysql.close();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
